/*
 * Copyright (C) 2020 The LINN Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.juqimiao.linn.interception;

import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 保存拦截器信息的类。
 *
 * @author  Collin Cai
 */
@Component
public class InterceptorKeeper implements InterceptorKeeperI {

    /**
     * 保存前置拦截器。
     */
    private Map<String, List<InterceptorI>> preInterceptors = new HashMap<>();
    /**
     * 保存后置拦截器。
     */
    private Map<String, List<InterceptorI>> postInterceptors = new HashMap<>();

    /**
     * 获取前置拦截器的集合。
     *
     * @return 一个前置拦截器的 Map。
     */
    @Override
    public Map<String, List<InterceptorI>> getPreInterceptors() {
        return this.preInterceptors;
    }

    /**
     * 获取后置拦截器的集合。
     *
     * @return 一个后置拦截器的 Map。
     */
    @Override
    public Map<String, List<InterceptorI>> getPostInterceptors() {
        return this.postInterceptors;
    }

    /**
     * 根据拦截器识别接口获得特定的拦截器集合。
     *
     * @param interceptorClz   用于特定组件的拦截器接口类型。
     * @param isPreInterceptor 指示是否是前置拦截器。
     * @param <T>              特定的拦截器接口类型。
     * @return 所有实现特定拦截器接口的具体拦截器集合。
     */
    @Override
    public <T> List<T> getInterceptors(Class<?> interceptorClz, boolean isPreInterceptor) {
        Map<String, List<InterceptorI>> matchingList = isPreInterceptor ? preInterceptors : postInterceptors;

        List<T> list = new ArrayList<>();
        if (matchingList.size() > 0) {
            List<InterceptorI> temp = matchingList.getOrDefault(interceptorClz.getName(), new ArrayList<>());
            Collections.sort(temp, Comparator.comparingInt(t -> t.getOrder()));
            if (temp != null && temp.size() > 0) {
                temp.forEach(item -> {
                    //The conversion may be failed, because of the object don't implement {@link InterceptorI}.
                    list.add((T) item);
                });
            }
        }

        return list;
    }
}
